package com.hjh.thymeleafdemo1.web;

import com.hjh.thymeleafdemo1.Service.DeptService;
import com.hjh.thymeleafdemo1.Service.UserService;
import com.hjh.thymeleafdemo1.entity.Dept;
import com.hjh.thymeleafdemo1.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private DeptService deptService;

    //负责跳转到首页
    @GetMapping("/toIndex")
    public String toIndex(){
        return "index";
    }


//    @GetMapping(value = "/list")
////    public String findUsers(String usrName, Long roleId, Model model){
////        List<User> list = userService.findAllUsers();
////        model.addAttribute("users",list);
////        return "/user/list";
////    }

    @GetMapping(value = "/list")
    public String quwapperUser( Model model){
        List<User> list = userService.findAllUsers();
        model.addAttribute("users",list);
        return "list";
    }

    @GetMapping("/add")
    public String toAdd(Model model){
        List<Dept> deptList = deptService.queryAllDept();
        model.addAttribute("depts",deptList);
        return "add";
    }

    @PostMapping("/save")
    public String addSave(User user){
        boolean success = userService.insertUser(user);
        if (success){
            return "redirect:/user/list";
        }
        return "redirect:/add";
    }

    @GetMapping(value = "/modify/{id}")
    public String update(@PathVariable("id") Long id, Model model){
        User user = userService.getUser(id);
        List<Dept> deptList  = deptService.queryAllDept();
        model.addAttribute("user", user);
        model.addAttribute("depts",deptList);
        return "add";
    }

    @PutMapping(value = "/save")
    public String updateSave(User user){
        int result = userService.updateUser(user);
        if(result > 0){
            return "redirect:/user/list";
        } else {
            return "redirect:/add/"+user.getId();
        }
    }

    @DeleteMapping("/delete/{id}")
    public String delUser(@PathVariable("id")long id){
        boolean isFlag = userService.deleteUser(id);
        if (isFlag){
            return "redirect:/user/list";
        }else{
            return "redirect:/user/list";
        }
    }
}
